<?php
namespace app\lib\model;

use EasyWeChat\Factory;
use think\facade\Cache;
use app\lib\exception\TokenException;
use think\facade\Request;
use app\web\model\User;
use app\web\model\Shop;
use app\web\model\Technician;
use app\web\model\Config;
/**
* 581917b58649646b895d553c784c090a
*/
class Token
{
        // 获取公众号用户信息
    // @route('/api/user/get_mp_user/:code','get')
    public function get_mp_user($code){
        
        $config = Config::getWechatConfig();
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$config['app_id'].'&secret='.$config['secret'].'&code='.$code.'&grant_type=authorization_code';

        $arr = curl_send($url,[],[],false);
       
        if(empty($arr['openid'])){
            throw new TokenException(['code'=>500,'msg'=>'登录失败']);
        }
        $token = $arr['access_token'];
        $openid = $arr['openid'];
        //拿到token后就可以获取用户基本信息了
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$openid;
        $arr = curl_send($url,[],[],false); //获取微信用户基本信息

        if(empty($arr['nickname'])){
            return make_return_json(500,'获取信息失败');
        }
        $arr['openid'] = $openid;
        return $arr;
    }
    /**
     * 小程序获取token
     * [get description]
     * @param  [type] $code [description]
     * @return [type]       [description]
     */
    public function get($mobile,$code='',$user_id = 0)
    {
        $client = Config::getClient();
        if($client == 0 && !$code){
            throw new TokenException(['code'=>500,'msg'=>'缺少参数code']);
        }
        if($client == 1){
            $session = $this->get_mp_user($code);
        }
        if($code && $client == 0){
            try{
                $app = Factory::miniProgram(Config::getWechatConfig());
                $session = $app->auth->session($code);
                if(empty($session['unionid'])){
                    throw new TokenException(['code'=>500,'msg'=>'appid未加入开放平台']);
                }
            }catch(\Exception $e){
                throw new TokenException(['code'=>500,'msg'=>'登陆失败'.$e->getMessage()]);
            }
        }
        $user = User::where('mobile',$mobile)->find();
        $appkey = Config::getAppKey();
        if(!$user){
            $add_data = ['mobile'=>$mobile,'p_id'=>$user_id,'openid1'=>$session['openid'],'nickName'=>isset($session['nickname']) ? $session['nickname'] : '','avatarUrl'=>isset($session['headimgurl']) ? $session['headimgurl']:''];
             $add_data[['openid','openid1'][$client]] = $session['openid'];
             $add_data['unionid'] = isset($session['unionid']) ? $session['unionid'] : '';
            if($code && $client == 0){
                $add_data['token'] = $session['unionid'];
               
            }else{
                $add_data['token'] = $this->generateToken();
            }
            $user = User::create($add_data);
        }else{
            if($client == 0){
                $user->unionid = $session['unionid'];
                if($appkey == 0) $user->openid = $session['openid'];
                
            }else{
                $user->unionid = isset($session['unionid']) ? $session['unionid'] : '';
                if($appkey == 0) $user->openid1 = $session['openid'];
            }
            $user->save();
        }

        if($appkey == 1){  //技师端
            $technician = Technician::where('user_id',$user->id)->find();
            if(!$technician){
                $add_technician_data = ['user_id'=>$user->id];
                $add_technician_data[['openid','openid1'][$client]] = $session['openid'];
                $technician = Technician::create($add_technician_data);
            }else{
                if($client == 1){
                    $technician->openid1 = $session['openid'];
                }else{
                    $technician->openid = $session['openid'];
                }
                $technician->save();
            }
        }elseif($appkey == 2){   //商家端
            $shop_id = input('shop_id',0);
            $auth_status = input('auth_status',0);
            $shop = Shop::where('user_id',$user->id)->find();
            if(!$shop){
                $add_shop_data = ['user_id'=>$user->id,'p_id'=>$shop_id,'auth_status'=>$auth_status];
                $add_shop_data[['openid','openid1'][$client]] = $session['openid'];
                $shop = Shop::create($add_shop_data);
            }else{
                if($client == 1){
                    $shop->openid1 = $session['openid'];
                }else{
                    $shop->openid = $session['openid'];
                }
                $shop->save();
            }
        }
        return ['token'=>$user['token'],'user_id'=>$user['id']];
    }
    /**
     * 获取用户信息
     * [getCurrentTokenVar description]
     * @param  [type] $key [description]
     * @return [type]      [description]
     */
    public static function getCurrentTokenVar($key)
    {
        $token = Request::instance()->header('token');
        $vars = Cache::get($token);
        if (!$vars){
            throw new TokenException(['code'=>500,'msg'=>'尝试获取的Token变量并不存在']);
        }
        else {
            if(!is_array($vars))
            {
                $vars = json_decode($vars, true);
            }
            if (array_key_exists($key, $vars)) {
                return $vars[$key];
            }
            else{
                throw new TokenException(['code'=>500,'msg'=>'尝试获取的Token变量并不存在']);
            }
        }
    }
    public static function verifyToken()
    {
        $token = Request::instance()->header('token');
        if($token == 'my_admin') return 1;
        $exist = Cache::get($token);
        return $exist ? true : false;
    }
    public function getToken($user){
        $key = $this->generateToken();
        $result = Cache::set($key,$user); //7天免登陆
        if(!$result){
            return false;
        }
        return $key;
    }
    /**
     * 重置token过期时间 重置token缓存信息
     * [tokenInc description]
     * @return [type] [description]
     */
    public static function tokenInc($user = null){
        $token = Request::instance()->header('token');
        if($token == 'my_admin') return true;
        if(!$token) return false;
        if($user){
            $result = Cache::set($token,$user,7100);
            if(!$result){
                return false;
            }
            return true;
        }
        $exist = Cache::get($token);
        if(!$exist) return false;
        $result = Cache::set($token,$exist,7100);
        if(!$result){
            return false;
        }
        return true;
    }
    private function generateToken(){
        $randChar = rand_string(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        return md5($randChar.$timestamp);
    }
}